<template>
  <px-card shadow="never">
    <px-scrollbar>
      <div class="flex-row-button">
        <px-button type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
        <div>
          <!-- <px-button v-if="taskDetailData.workOrderStatus === 2 && userId === taskDetailData.createBy" type="primary" @click="handleCreateEdit">
            再次编辑
          </px-button> -->
          <!-- <px-button v-if="taskDetailData.workOrderStatus === 1 && userId === taskDetailData.createBy" type="primary" @click="handleBack">
            撤回任务
          </px-button> -->
          <px-button
            v-if="drawerType !== 'view' && taskDetailData.workOrderStatus === 3 && (taskDetailData.createBy === userId || taskDetailData.isInGroup)"
            type="primary"
            @click="handleCancel"
          >
            退回任务
          </px-button>
          <px-button
            v-if="drawerType !== 'view' && taskDetailData.workOrderStatus === 3 && taskDetailData.isInGroup"
            type="primary"
            @click="handleCollect"
          >
            确认领取维修任务
          </px-button>
          <px-button
            v-if="drawerType !== 'view' && taskDetailData.workOrderStatus === 1 && userId === taskDetailData.approverId"
            type="primary"
            @click="handleAudit"
          >
            审批
          </px-button>
          <px-button
            v-if="drawerType !== 'view' && taskDetailData.workOrderStatus === 5 && userId === taskDetailData.supervisorId"
            type="primary"
            @click="handleCheck"
          >
            验收
          </px-button>
          <!-- <px-button
            v-if="drawerType !== 'view' && [4, 6].includes(taskDetailData.workOrderStatus) && userId === taskDetailData.executorId"
            type="primary"
            @click="handleFinish"
          >
            完成维修
          </px-button> -->
          <!-- <px-button
            v-if="!drawerType && [6].includes(taskDetailData.workOrderStatus) && userId === taskDetailData.executorId"
            type="primary"
            @click="handleExecutorEdit"
          >
            再次编辑
          </px-button> -->
        </div>
      </div>
      <div class="view-equip-title">基础信息</div>
      <div class="view-equip-wrap">
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">设备编码</div>
            <div class="text">{{ taskDetailData.eqpId }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">设备名称</div>
            <div class="text">{{ taskDetailData.eqpName }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">设备位置</div>
            <div class="text">{{ taskDetailData.positionName }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">科室</div>
            <div class="text">{{ taskDetailData.classNameDesc }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">系统</div>
            <div class="text">{{ taskDetailData.systemCodeDesc }}</div>
          </div>
          <div class="view-equip-item">
            <div class="label">报修人</div>
            <div class="text">{{ taskDetailData.createName }}</div>
          </div>
        </div>
        <div class="view-equip-content">
          <div class="view-equip-item">
            <div class="label">报修时间</div>
            <div class="text">{{ taskDetailData.createTime }}</div>
          </div>
          <div class="view-equip-item large">
            <div class="label">维修状态</div>
            <div class="text">
              <div class="status">
                <div class="circle" :style="{ backgroundColor: `${tagBgColorList[taskDetailData.workOrderStatus]}` }" />
                <p :style="{ color: `${tagBgColorList[taskDetailData.workOrderStatus]}` }">{{ taskDetailData.workOrderStatusDesc }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <CustomTabs v-model:activeName="activeName" :tabList="tabList" :before-leave="handleBeforeLeave" />
      <FaultInfo v-if="activeName === 'first'" :taskDetailData="taskDetailData" />

      <MaintainInfo
        v-if="activeName === 'second' || preName === 'second'"
        v-show="activeName === 'second'"
        v-model:preName="preName"
        :status="taskDetailData.workOrderStatus"
        :taskId="taskId"
        :userId="userId"
        :activeName="activeName"
        :drawerType="drawerTypeDetail"
        @backMainPage="backMainPage"
        @handleFinish="handleFinish"
      />

      <SparePartsTool
        v-if="activeName === 'third' || preName === 'third'"
        v-show="activeName === 'third'"
        v-model:preName="preName"
        :taskId="taskId"
        :userId="userId"
        :activeName="activeName"
        :drawerType="drawerTypeDetail"
        :className="taskDetailData.className"
        :taskDetailData="taskDetailData"
        @backMainPage="backMainPage"
        @handleFinish="handleFinish"
      />
      <MaintainMeans
        v-if="activeName === 'forth' || preName === 'forth'"
        v-show="activeName === 'forth'"
        v-model:preName="preName"
        v-model:fileStatusFlag="isRejectLeave"
        :taskId="taskId"
        :userId="userId"
        :activeName="activeName"
        :taskDetailData="taskDetailData"
        :drawerType="drawerTypeDetail"
        @backMainPage="backMainPage"
        @handleFinish="handleFinish"
      />
      <DealProcess
        v-if="activeName === 'fifth'"
        :taskId="taskId"
        :userId="userId"
        :activeName="activeName"
        @backMainPage="backMainPage"
        @handleFinish="handleFinish"
      />
      <!--审批/验收弹窗-->
      <px-dialog v-model="isAuditShow" :title="isAudit ? '审批' : '验收'" width="600px" destroy-on-close append-to-body @close="handleCancelAudit">
        <px-form ref="auditRef" :model="auditForm" :rules="rules" label-width="120px">
          <px-form-item :label="isAudit ? '审批人' : '验收人'" prop="approverName">
            <px-input v-model="auditForm.approverName" disabled />
          </px-form-item>
          <px-form-item :label="isAudit ? '审批结果' : '验收结果'" prop="approvalResult">
            <px-select v-model="auditForm.approvalResult" style="width: 100%" placeholder="请选择" clearable>
              <px-option v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
          <px-form-item :label="isAudit ? '审批意见' : '验收意见'" prop="approvalOpinion">
            <px-input
              v-model="auditForm.approvalOpinion"
              :autosize="{ minRows: 2, maxRows: 4 }"
              maxlength="1000"
              type="textarea"
              placeholder="请输入"
            />
          </px-form-item>
        </px-form>
        <template #footer>
          <div class="dialog-footer">
            <px-button @click="handleCancelAudit">取消</px-button>
            <px-button type="primary" @click="handleSubmitAuditForm(auditRef)">确定</px-button>
          </div>
        </template>
      </px-dialog>
      <!--取消任务弹窗-->
      <px-dialog v-model="isCancelShow" title="取消任务" width="600px" destroy-on-close append-to-body @close="handleCancelCancel">
        <px-form ref="cancelRef" :model="cancelForm" label-position="top">
          <px-form-item
            label="取消原因"
            prop="reason"
            :rules="[
              {
                required: true,
                message: '请输入取消原因',
                trigger: 'blur'
              }
            ]"
          >
            <px-input
              v-model="cancelForm.reason"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 8 }"
              maxlength="1000"
              clearable
              placeholder="请输入"
              show-word-limit
            />
          </px-form-item>
        </px-form>
        <template #footer>
          <div class="dialog-footer">
            <px-button @click="handleCancelCancel">取消</px-button>
            <px-button type="primary" @click="handleSubmitCancelForm(cancelRef)">确定</px-button>
          </div>
        </template>
      </px-dialog>
      <!-- 完成确认弹窗 -->
      <FinishDialog
        :visible="isFinishShow"
        :tabName="tabName"
        :taskDetailData="taskDetailData"
        @closeDialog="isFinishShow = false"
        @handleFinishBack="handleFinishBack"
      />
    </px-scrollbar>
  </px-card>
</template>

<script lang="ts" setup>
import {
  auditMaintainList,
  cancelMaintainList,
  checkMaintainList,
  collectMaintainList,
  detailMaintainList,
  queryMaintenanceInfo
} from "@/api/equip/maintain";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watchEffect } from "vue";
import { useRoute, useRouter } from "vue-router";
import DealProcess from "./DealProcess.vue";
import FaultInfo from "./FaultInfo.vue";
import FinishDialog from "./FinishDialog.vue";
import MaintainInfo from "./MaintainInfo.vue";
import MaintainMeans from "./MaintainMeans.vue";
import SparePartsTool from "./SparePartsTool.vue";
import CustomTabs from "./Tabs.vue";

const emits = defineEmits(["handleGoToEdit"]);

const route = useRoute();
const router = useRouter();

const auditRef = ref();
const cancelRef = ref();

const optionsList = [
  {
    label: "通过",
    value: "pass"
  },
  {
    label: "驳回",
    value: "reject"
  }
];

const tagBgColorList = {
  0: "#909399", // 草稿
  1: "#F59E0B", // 待审批
  2: "#EF4444", // 审批驳回
  3: "#F59E0B", // 待接单
  4: "#3B82F6", // 执行中
  5: "#F59E0B", // 待验收
  6: "#EF4444", // 验收驳回
  7: "#909399", // 取消
  8: "#10B981" // 已完成
};

const activeName = ref("first");

const state = reactive<Record<string, any>>({
  taskDetailData: [],
  isAuditShow: false,
  isCancelShow: false,
  isAudit: true, // 是验收还是审批
  isFinishShow: false,
  auditForm: {},
  cancelForm: {},
  userId: "",
  userInfo: {},
  drawerTypeDetail: "",
  taskId: "",
  preName: "",
  drawerType: "",
  tabName: 0,
  isRejectLeave: false
});
const {
  taskDetailData,
  isAuditShow,
  isCancelShow,
  isAudit,
  isFinishShow,
  auditForm,
  cancelForm,
  userId,
  userInfo,
  drawerTypeDetail,
  taskId,
  preName,
  drawerType,
  tabName,
  isRejectLeave
} = toRefs(state);

const tabList = computed(() => {
  return [4, 5, 6, 8].includes(taskDetailData.value.workOrderStatus)
    ? [
        {
          name: "first",
          label: "故障信息"
        },
        {
          name: "second",
          label: "维修结果"
        },
        {
          name: "third",
          label: "备件/工具"
        },
        {
          name: "forth",
          label: "维修资料"
        },
        {
          name: "fifth",
          label: "维修进度"
        }
      ]
    : [
        {
          name: "first",
          label: "故障信息"
        },
        {
          name: "fifth",
          label: "维修进度"
        }
      ];
});

const handleBeforeLeave = (cur, old) => {
  if (isRejectLeave.value) {
    PxMessage.warning("请上传完成后操作");
    return false;
  }
  activeName.value = cur;
  preName.value = old;
};

// 表单校验规则
const rules = computed(() => ({
  approvalResult: [{ required: true, message: "请选择审批结果", trigger: ["blur", "change"] }]
}));

const getDetailData = async () => {
  const res = await detailMaintainList({ id: taskId.value });
  if (res) {
    const { repairImageList, workOrderStatus } = res;
    taskDetailData.value = { ...res, repairImageList: repairImageList || [] };
    if ([5, 6].includes(workOrderStatus)) {
      const maintainInfo = await queryMaintenanceInfo({ workOrderId: taskId.value });
      const { isSupervised } = maintainInfo || {};
      taskDetailData.value = { ...taskDetailData.value, isSupervised };
    }
    // 如果外层点击资料补充，则进到这个页面
    if (drawerType.value === "file") {
      activeName.value = "forth";
    }
    // 如果外层点击执行中，则进到这个页面
    else if (drawerType.value === "execute") {
      activeName.value = "second";
    }
    drawerTypeDetail.value = drawerType.value;
  }
};
// watch(
//   () => route.query.id,
//   (newVal, oldVal) => {
//     console.log(route.query);
//     if (newVal && newVal !== oldVal) {
//       const { id, type } = route.query;
//       drawerType.value = type;
//       taskId.value = id;
//       const tempUserInfo = JSON.parse(localStorage.getItem("userInfo"));
//       userInfo.value = tempUserInfo;
//       userId.value = tempUserInfo.userId;
//       getDetailData();
//     }
//   },
//   {
//     immediate: true
//   }
// );

watchEffect(() => {
  const { id, type, tabName: name } = route.query;
  if (id) {
    drawerType.value = type;
    taskId.value = id;
    tabName.value = name;
    const tempUserInfo = JSON.parse(localStorage.getItem("userInfo"));
    userInfo.value = tempUserInfo;
    userId.value = tempUserInfo.userId;
    getDetailData();
  }
});

// 返回主页面
const backMainPage = () => {
  const reg = /^[a-zA-Z]+:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})((:\d+)?)/;
  const res = document.referrer.replace(reg, ""); // 需要拿到来源页面的path路径
  if (tabName.value) {
    router.push(`/all/equip/maintain/task?tabName=${tabName.value}`);
  } else {
    router.push(res);
  }
};

// const handleBack = () => {
//   PxMessageBox.confirm(`确认撤回维修任务吗？撤回后任务回归为草稿`, "提示", {
//     type: "warning"
//   })
//     .then(async () => {
//       await backMaintainList({ id: taskId.value });
//       PxMessage.success("撤回成功");
//       backMainPage();
//     })
//     .catch(() => {});
// };
const handleCancel = () => {
  isCancelShow.value = true;
};

const handleCollect = () => {
  PxMessageBox.confirm(`确认领取维修任务吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    draggable: true,
    type: "warning"
  })
    .then(async () => {
      await collectMaintainList({ workOrderId: taskId.value });
      await getDetailData();
      activeName.value = "second";
      PxMessage.success("领取成功");
      drawerTypeDetail.value = "execute";
    })
    .catch(() => {});
};

const handleCheck = () => {
  auditForm.value.approverName = userInfo.value.realName;
  isAuditShow.value = true;
  isAudit.value = false;
};
const handleAudit = () => {
  auditForm.value.approverName = userInfo.value.realName;
  isAuditShow.value = true;
};
// 完成维修
const handleFinish = () => {
  PxMessageBox.confirm(`请确认已经保存当前页进度，否则内容可能会丢失`, "提示", {
    confirmButtonText: "完成维修",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      isFinishShow.value = true;
    })
    .catch(() => {});
};
const handleFinishBack = () => {
  backMainPage();
};

const handleCancelAudit = () => {
  auditRef.value.resetFields();
  isAuditShow.value = false;
  isAudit.value = true;
};

// const handleExecutorEdit = () => {
//   drawerType.value = "execute";
//   drawerTypeDetail.value = "execute";
//   activeName.value = "second";
// };

// const handleCreateEdit = () => {
//   emits("handleGoToEdit", taskId.value);
// };
/** 提交按钮 */
const handleSubmitAuditForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (isAudit.value) {
        await auditMaintainList({ workOrderId: taskId.value, ...auditForm.value, approverId: userId.value });
        PxMessage.success("审批成功");
        isAuditShow.value = false;
        backMainPage();
      } else {
        await checkMaintainList({ workOrderId: taskId.value, ...auditForm.value, approverId: userId.value });
        PxMessage.success("验收成功");
        isAuditShow.value = false;
        backMainPage();
      }
    }
  });
};

const handleCancelCancel = () => {
  cancelRef.value.resetFields();
  isCancelShow.value = false;
};

const handleSubmitCancelForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      await cancelMaintainList({ id: taskId.value, ...cancelForm.value });
      PxMessage.success("取消成功");
      handleCancelCancel();
      backMainPage();
    }
  });
};
</script>
<style lang="scss" scoped>
@import url("./style.scss");

.flex-row-button {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.status {
  display: flex;
  flex-direction: row;
  align-items: center;

  .circle {
    width: 8px;
    height: 8px;
    margin-right: 5px;
    border-radius: 50%;
  }
}
</style>
